from .models import User
from rest_framework import serializers
<<<<<<< HEAD
import re
from rest_framework.validators import ValidationError


class UserSer(serializers.ModelSerializer):
    password = serializers.CharField(max_length=64, write_only=True, trim_whitespace=True)
=======
from rest_framework.validators import ValidationError
from django.contrib.auth.hashers import make_password
import re


class UserSer(serializers.ModelSerializer):
    password = serializers.CharField(max_length=64, write_only=True, required=True, trim_whitespace=True)

    # 反序列化时， 对数据的全局验证
    def validate(self, data):
        print("验证数据中...", data)
        # 获取数据
        username = data.get("username")
        password = data.get("password")
        mobile = data.get("mobile")
        email = data.get("email")

        # 验证用户名，用户名包含字母、数字、下划线，长度为5-20
        if not re.findall(r"^\w{5,20}$", username):
            raise ValidationError("用户名需包含字母、数字、下划线，长度为5-20")
        # 验证密码
        elif not re.findall(r"^[\w!@#$%^&*]{8,20}$", password):
            raise ValidationError("密码是8到20位数字、字母或下划线以及特殊!@#$%^&*符号")

        # 验证手机号
        elif not re.findall(r"^1[34578]\d{9}$", mobile):
            raise ValidationError("手机格式不正确")

        else:
            # 验证通过， 返回数据
            return data

    # 重写create方法， 密码需要hash加密
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        user.set_password(validated_data.get("password"))
        user.save()
        return user

    class Meta:
        model = User
        fields = ["id", "username","password", "mobile", "email"]
        read_only_fields = ["id",]


>>>>>>> f03f6fc2a5e389c57682ccb2441daf9bc7b6dbf9

    # 重写验证方法， 添加自己的验证规则
    def validate(self, data):
        username = data.get("username")
        password = data.get("password")
        mobile = data.get("mobile")
        email = data.get("email")

        # 验证用户名是否满足要求
        if not re.findall(r"^\w{5,20}$", username):
            raise ValidationError("用户名是5到20位数字、字母或下划线")

        # 验证密码是否满足要求
        if not re.findall(r"^[\w!@#$%^&*]{8,20}$", password):
            raise ValidationError("密码是8到20位数字、字母或下划线以及特殊!@#$%^&*符号")

        # 验证手机号
        if not re.findall(r"^1[34578]\d{9}$", mobile):
            raise ValidationError("手机格式不正确")

        return data

    # 重写create方法，实现用户数据的保存
    def create(self, validated_data):
        # 保存用户对象
        user = User.objects.create_user(**validated_data)
        #
        #         # 更新密码为哈希加密的
        #         # user.set_password(validated_data.get("password"))

        return user


    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'mobile', 'email']
        read_only_fields = ["id",]


